<?php
include_once(APP_PATH."/cartoon/global.php");
class cartoon_model_data extends cartoon_model_bmodel {
	
	private $cache;
	
	public function __construct(){
		parent::__construct();
		
		$this->cache = new cartoon_util_cache();
		
		$this->table = 'cartoon_cartoon';	//漫画表
	}
	
	/**
	 * 添加漫画
	 *
	 * @param unknown_type $para
	 * @return unknown
	 */
	public function add($para){
		return $this->db->insert($this->table,$para);
		if($rs = $this->db->insert($this->table,$para)){
			member_util_interface::getUserCount($para['ct_uid'],true);
			return $rs;
		}
		return $rs;
	}
	
	public function remove($cid){
		if(!$cid) return false;
		$cid = is_array($cid)?implode(',',$cid):$cid;
		/**
		 * 删除相关信息
		 */
		if($this->db->query("DELETE FROM cartoon_chapter WHERE cartoon_id IN ($cid)")){
			$this->db->query("DELETE FROM cartoon_images WHERE img_cartoon_id IN ($cid) ");
			return $this->db->query("DELETE FROM $this->table WHERE id IN($cid)");
		}
	}
	
	
	/**
	 * 根据id获取漫画信息
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	public function getRow($id){
		if(is_numeric($id)){
			return $this->db->fetchRow("SELECT * FROM $this->table WHERE id=$id");
		}
		return false;
	}
	
	/**
	 * 根据漫画id列表，获取所有的漫画
	 *
	 * @param unknown_type $id
	 */
	public function getAll($id){
		$id = is_array($id)?implode(',',$id):$id;
		
		return $this->db->fetchAll("SELECT * FROM $this->table WHERE id IN ($id)");
		
	}
	
	/**
	 * 缓存获取漫画信息
	 *
	 * @param unknown_type $cartoon_id
	 * @param unknown_type $flush
	 */
	public function getCartoonInfo($cartoon_id,$flush = false){
		if(!is_numeric($cartoon_id)) return false;
		$key = CACHE_PRE_CARTOON.$cartoon_id;
		if(!($info = MemRow::getCache($key)) || $flush == true){
			$info = self::getRow($cartoon_id);
			MemRow::setCache($key,$info,0);
		}
		return $info;
	}
	
	public function incrField($cartoon_id,$filed){
		if(!($cartoon_id && $filed)) return false;
		if($this->db->query("UPDATE $this->table  SET $filed = $filed+1 WHERE id = $cartoon_id")){
			$this->getCartoonInfo($cartoon_id,true);
		}
	}
	/**
	 * 更新漫画的评论数
	 *
	 * @param unknown_type $cartoon_id
	 * @return unknown
	 */
	public function upCartoonComments($cartoon_id){
		if(!$cartoon_id) return false;
		if($this->db->query("UPDATE $this->table  SET ct_comments = ct_comments+1 WHERE id = $cartoon_id")){
			$this->getCartoonInfo($cartoon_id,true);
		}
	}
	
	/**
	 * 更新漫画的dig数
	 *
	 * @param unknown_type $cartoon_id
	 * @return unknown
	 */
	public function upCartoonDigs($cartoon_id){
		if(!$cartoon_id) return false;
		if($this->db->query("UPDATE $this->table  SET ct_tops = ct_tops+1 WHERE id = $cartoon_id")){
			$this->getCartoonInfo($cartoon_id,true);
		}
	}
	
	/**
	 * 更新漫画章节数
	 * @param uint $cartoon_id  漫画id
	 * @param uint $num		更新数量
	 */
	public function upChapterNum($cartoon_id,$num=1){
		if(!is_numeric($cartoon_id)) return false;
		$sql = "UPDATE $this->table SET ct_chapters = ct_chapters+$num,ct_update=".CURRENT_TIME.' WHERE id='.$cartoon_id;
		if($this->db->query($sql)){
			$this->getCartoonInfo($cartoon_id,true);
		}
	}

	/**
	 * 获取我浏览的章节列表
	 *
	 * @param unknown_type $uid
	 * @return unknown
	 */
	public function getMyLogs($uid){
		if(!$uid) return false;
		$sql = " SELECT cartoon_id,chapter_id FROM cartoon_readlog WHERE uid = $uid ";
		return $this->db->fetchAll($sql);
	}

    /**
     * @desc 获取漫画列表
     * @param  int $cateid
     * @return array
     */
    public function getListByCate($cateid,$num = 8){
        if(!$cateid) return false;
        $cateid = is_array($cateid)?implode(',',$cateid):$cateid;
        $sql = "SELECT * FROM $this->table WHERE ct_category IN ($cateid) ORDER BY id DESC LIMIT $num ";
        return $this->db->fetchALL($sql);
    }

	/**
	 * 设置漫画状态
	 *
	 * @param unknown_type $cartoon_id
	 * @param unknown_type $flag
	 */
	public function recomCartoon($cartoon_id,$flag){
		if(!$cartoon_id) return false;
		!$flag && $flag = 0;
		$cartoon_id = is_array($cartoon_id)?$cartoon_id:explode(',',$cartoon_id);
		$sql = "UPDATE $this->table SET ct_recoment = $flag WHERE id IN(".implode(',',$cartoon_id).")";
		if($this->db->query($sql)){	
			foreach ($cartoon_id as $v){
				self::getCartoonInfo($v,true);
			}
			return true;
		}
		else return false;
	}
	/**
	 * 搜索漫画
	 *
	 * @param unknown_type $k
	 */
    public function search($k,$page = 1,$pageSize = 15){
    	$sql = "SELECT * FROM $this->table WHERE 1 ";
    	if($k){
    		$sql .= " AND (ct_title LIKE '%$k%' OR ct_author LIKE '%$k%' )";
    	}
    	$sql.=" ORDER BY ct_update DESC";
    	return $this->db->selectPage($sql,array(),$page,$pageSize);
    }
	
	/**
	 * 根据条件，获取漫画列表
	 *
	 * @param unknown_type $para
	 * @param unknown_type $page
	 * @param unknown_type $pageSize
	 */
	public function getCartoonList($args = array(),$page=1,$pageSize=CT_PAGE_SIZE){
		$sql = "SELECT * FROM $this->table  ";
		$where = ' WHERE 1 ';
		if($args['cartoon_flag']){
			$where.=' AND cartoon_flag = '.$args['cartoon_flag'];
		}
		if($args['ct_recoment'])  $where.=' AND ct_recoment = '.$args['ct_recoment'];
		if($args['ct_category'])  $where.=' AND ct_category LIKE \'%'.$args['ct_category'].'%\'';
		if($args['uid']) $where.=' AND ct_uid = '.$args['uid'];
		$sql.=$where.' ORDER BY id DESC ';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}	
	
	/**
	 * 获取推荐的漫画类表
	 * @param  int $flag 推荐状态 	
	 * @param  int $num	推荐的数量
	 * @return unknown
	 */
	public function getCartoonListRecom($flag = CONST_CT::RECOM_HOME,$num = 8,$order = ''){
		!$flag && $flag = CONST_CT::RECOM_HOME;
		!$num && $num = 8;
		$sql = " SELECT * FROM $this->table WHERE ct_recoment = $flag  ORDER BY ".($order?$order:' ct_update ').' DESC LIMIT '.$num ;
		return $this->db->fetchAll($sql);		
	}
	
	/**
	 * 获取最新的漫画列表
	 *
	 * @param unknown_type $num
	 */
	public function getCartoonListNew($num = 4,$order = null){
		$sql = " SELECT * FROM $this->table WHERE  1 ORDER BY ".($order?$order:' id ').' DESC LIMIT '.$num ;
		return $this->db->fetchAll($sql);
	}
	
	/**
	 * 获取推荐的漫画类表
	 * @param  int $flag 推荐状态 	
	 * @param  int $num	推荐的数量
	 * @return unknown
	 */
	public function getCTListRecomPage($flag = CONST_CT::RECOM_HOME,$page = 1,$pageSize = 15){
		!$flag && $flag = CONST_CT::RECOM_HOME;
		$sql = " SELECT * FROM $this->table WHERE ct_recoment = $flag  ORDER BY  ct_update  DESC " ;
		return $this->db->selectPage($sql,array(),$page,$pageSize);		
	}

	
	/**
	 * 根据分类获取tag类表
	 *
	 * @param tinyint $type
	 * @return array();
	 */
	
	public function cacheGetTagByType($type){
		if(!in_array($type,array_keys($_SERVER['cartoon']['tag_type']))) return false;
		
		$rs = $this->cacheGetTags();
		
		return $rs[$type];
	}
	
	
	
	/**
	 * 根据类型获取标签
	 *
	 * @param unknown_type $type
	 * @return unknown
	 */
	
	public function getTagByType($type=NULL){
		$sql = "SELECT * FROM cartoon_tags ";
		if($type && in_array($type,array_keys($_SERVER['cartoon']['tag_type']))){
			$sql.=' WHERE tag_type = '.$type;
		}
		
		$return  = array();
				
		if($rs = $this->db->fetchAll($sql)){
			foreach ($rs as $row){
				$return[$row['tag_type']][$row['tag_id']] = $row;
			}
		}		
		return $return;
	}
	
	/**
	 * 设置用户阅读漫画记录表
	 *
	 * @param unknown_type $chapter_id
	 * @param unknown_type $cartoon_id
	 * @param unknown_type $uid
	 */
	public function readLog($cartoon_id,$chapter_id,$uid){
		if(!( $cartoon_id && $uid)) return false;
		$sql = "INSERT INTO cartoon_readlog (cartoon_id,uid,chapter_id,read_time) VALUES($cartoon_id,$uid,$chapter_id,".CURRENT_TIME.") ON DUPLICATE KEY UPDATE chapter_id = $chapter_id , read_time =".CURRENT_TIME;
		return $this->db->query($sql);
	}

    /**
     * 检查用户是否已经评分了
     * @param  $cartoon_id
     * @param  $uid
     * @return void
     */
    public function chkScore($cartoon_id,$uid){
        if(!($cartoon_id && $uid)) return false;
        $sql = "SELECT add_time FROM cartoon_scorelog WHERE cartoon_id=$cartoon_id AND uid=$uid";
        $rs = $this->db->fetchField($sql,'add_time');
        return $rs?true:false;
    }

    /**
	 * 给资源打分
	 *
	 * @param int $cartoon_id
	 * @param 用户uid $uid
	 * @param float $score
	 * @return unknown
	 */

    public function score($cartoon_id,$uid,$score = 1){
        if(!($cartoon_id && $uid)) return false;
        if($this->chkScore($cartoon_id,$uid)) {
        	return Error::ERROR_RECORD_EXISTS ;
        }
        $score = floatval($score);
        if($this->db->query("UPDATE $this->table SET ct_score = (ct_score*ct_score_num+$score)/(ct_score_num+1),ct_score_num=ct_score_num+1 WHERE id=$cartoon_id")){
        	$this->getCartoonInfo($cartoon_id,true);
            $this->db->query('INSERT INTO cartoon_scorelog VALUES  ('.$cartoon_id.','.$uid.','.CURRENT_TIME.')');
            return true;
        }
    }

    /**
	 * 根据uid获取评分记录
	 *
	 * @param int $uid
	 * @return unknown
	 */
	public function getScoreList($uid){
		if(!$uid) return false;
		$resid = array();
		if($rs = $this->db_active->fetchAll("SELECT cartoon_id FROM cartoon_scorelog WHERE uid=$uid")){
			while ($row = current($rs)) {
				array($resid,$row['cartoon_id']);
				next($rs);
			}
		}
		return $resid;
	}

	/**
	 * 添加分类
	 *
	 * @param unknown_type $title
	 * @param unknown_type $order
	 * @return unknown
	 */
	public function addCate($title,$order = 0,$flag = 1){
		if(!$title) return false;
		if($this->chkCate($title)) return ERR_EXISTS;
		return $this->db->insert('cartoon_category',array('cate_name'=>$title,'cate_pid'=>0,'cate_order'=>$order,'cate_flag'=>$flag,'cate_time'=>CURRENT_TIME));
	}
	
	/**
	 * 修改分类
	 *
	 * @param array $args
	 * @return boolean
	 */
	public function editCate($args){
		if(!$args['id']) return false;
		return $this->db->update('cartoon_category',$args);
	}
	
	/**
	 * 删除分类
	 *
	 * @param unknown_type $cateid
	 * @return unknown
	 */
	public function delCate($cateid){
		if(!$cateid) return false;
		$ids = is_array($cateid)?implode(',',$cateid):$cateid;
		if($this->db->query("DELETE FROM cartoon_category WHERE id IN ($cateid)")){
			//做其他处理
			cartoon_util_interface::cacheGetCateList(true);//更新缓存
			return true;
		}
		return false;
	}

	/**
	 * 检查分类是否已经存在
	 *
	 * @param unknown_type $title
	 * @return unknown
	 */
	public function chkCate($title){
		if(!$title) return false;
		if($rs = $this->db->fetchField("SELECT id FROM cartoon_category WHERE cate_name = '$title'",'id')){
			return true;
		}
		return false;
	}
	/**
	 * 漫画分类
	 *
	 * @return unknown
	 */
	public function getCateList($order = NULL){
		return $this->db->fetchAll("SELECT * FROM cartoon_category ORDER BY ".($order?$order:'cate_order,id').' DESC ');
	}
	
	/**
	 * 添加漫画作者
	 *
	 * @param unknown_type $args
	 */
	public function add_author($args){
		if(!$args['name']) return false;
		//判断作者名是否已经存在
		if($this->chk_author($args['name'])) return ERR_EXISTS;
		return $this->db->insert('cartoon_authors',$args);
	}
	/**
	 * 检查作者名是否已经存在
	 *
	 * @param unknown_type $name
	 * @return unknown
	 */
	public function chk_author($name){
		if(!$name) return false;
		$rs = $this->db->fetchField('SELECT id FROM cartoon_authors WHERE name = \''.$name.'\'','id');
		return $rs?true:false;
	}
	
	/**
	 * 修改作者
	 *
	 * @param unknown_type $args
	 * @return unknown
	 */
	public function edit_author($args){
		if(!$args['id'] or !$args['name']) return false;
		return $this->db->update('cartoon_authors',$args,array());
	}
	
	/**
	 * 获取作者列表
	 *
	 */
	public function getAuthorList(){
		$sql = "SELECT * FROM cartoon_authors ";
		return $this->db->fetchAll($sql);
	}
	
	/**
	 * 获取作者列表
	 *
	 */
	public function getAuthorListPages($args = array(),$page = 1,$pageSize = 15){
		$sql = "SELECT * FROM cartoon_authors ";
		if($args['nation']) $where = ' WHERE nation = \''.$args['nation'].'\'';
		if($args['name'])	$where = ($where?$where.' AND ':' WHERE ').'name = \''.$args['name'].'\'';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 添加dig记录
	 *
	 * @param int $uid
	 * @param int $cartoon_id
	 */
	public function addDig($uid,$cartoon_id){
		if(!($uid && $cartoon_id)) return false;
		if($this->chkDigLog($uid,$cartoon_id)) return Error::ERROR_RECORD_EXISTS;
		$sql = "INSERT INTO cartoon_diglog VALUES (NULL,$uid,$cartoon_id,".CURRENT_TIME.")";
		if($this->db->query($sql)){
			$this->incrField($cartoon_id,'ct_tops');
			return true;
		}
	}
	
	/**
	 * 检查是否已经dig过了
	 * @param int $uid
	 * @param int $cartoon_id
	 * @return unknown
	 */
	public function chkDigLog($uid,$cartoon_id){
		if($rs = $this->db->fetchField("SELECT id FROM cartoon_diglog WHERE uid=$uid AND cid = $cartoon_id ",'id')){
			return true;
		}
		return false;
	}
	/**
	 * 获取订阅的列表
	 *
	 * @param unknown_type $uid
	 */
	public function getSubList($uid,$page=1,$pageSize=15){
		$sql = "SELECT a.id,a.ct_title,a.ct_uid,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,a.ct_simple_desc,b.id as sub_id,b.add_time FROM ".$this->table.' a,cartoon_subscribe b
		       WHERE b.uid='.$uid.' AND a.id = b.cartoon_id  ORDER BY b.add_time DESC ';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 获取订阅的列表
	 *
	 * @param unknown_type $uid
	 */
	public function getSubListNew($uid,$num = 4){
		$sql = "SELECT a.id,a.ct_title,a.ct_uid,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,a.ct_simple_desc,b.id as sub_id,b.add_time FROM ".$this->table.' a,cartoon_subscribe b
		       WHERE b.uid='.$uid.' AND a.id = b.cartoon_id  ORDER BY b.add_time DESC LIMIT '.$num;
		
		return $this->db->fetchAll($sql);
	}
	
	/**
	 * 获取收藏的列表
	 *
	 * @param unknown_type $uid
	 */
	public function getCollectList($uid,$page=1,$pageSize=15){
		$sql = "SELECT a.id,a.ct_title,a.ct_uid,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,b.id as collect_id,b.add_time FROM ".$this->table.' a,cartoon_collect b
		       WHERE b.uid='.$uid.' AND a.id = b.cartoon_id  ORDER BY b.add_time DESC ';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 获取订阅的列表
	 *
	 * @param unknown_type $uid
	 */
	public function getViewList($uid,$page=1,$pageSize=15){
		$sql = "SELECT a.id,a.ct_title,a.ct_uid,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,a.ct_simple_desc,b.chapter_id,b.read_time FROM ".$this->table.' a,cartoon_readlog b
		       WHERE b.uid='.$uid.' AND a.id = b.cartoon_id  ORDER BY b.read_time DESC ';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	/**
	 * 获取浏览的漫画列表
	 *
	 * @param unknown_type $uid
	 * @param unknown_type $num
	 * @param unknown_type $distinct
	 * @return unknown
	 */
	public function getViewListNew($uid,$num = 4,$distinct = false){
		$uid = is_array($uid)?implode(',',$uid):$uid;
		$sql = "SELECT ".($distinct?' distinct a.ct_uid':'a.ct_uid')." ,a.ct_title,a.id,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,a.ct_simple_desc,b.chapter_id,b.read_time FROM ".$this->table.' a,cartoon_readlog b
		       WHERE b.uid IN ('.$uid.') AND a.id = b.cartoon_id  ORDER BY b.read_time DESC LIMIT '.$num ;
		return $this->db->fetchAll($sql);
//		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 获取评分的列表
	 *
	 * @param unknown_type $uid
	 */
	public function getscoreListPage($uid,$page=1,$pageSize=15){
		$sql = "SELECT a.id,a.ct_title,a.ct_uid,a.ct_cover,a.ct_last_chapterid,a.ct_last_chapter,b.add_time FROM ".$this->table.' a,cartoon_scorelog b
		       WHERE b.uid='.$uid.' AND a.id = b.cartoon_id  ORDER BY b.add_time DESC ';
		return $this->db->selectPage($sql,array(),$page,$pageSize);
	}
	
	/**
	 * 添加更新日志
	 *
	 * @param unknown_type $args
	 */
	public function addUpLog($args){
		return $this->db->insert('cartoon_up_log',$args);
	}
	
	/**
	 * 删除
	 *
	 * @param unknown_type $id
	 * @return unknown
	 */
	public function delUpLog($id){
		$id = is_array($id)?implode(',',$id):$id;
		return $this->db->query("DELETE FROM cartoon_up_log WHERE id IN ($id)");
	}
	
	/**
	 * 获取更细日志
	 *
	 * @return unknown
	 */
	public function getUpListPages($page = 1,$pageSize = 20){
//		return $this->db->fetchAll("SELECT * FROM cartoon_up_log ORDER BY id DESC LIMIT $num " );
		return $this->db->selectPage(" SELECT * FROM cartoon_up_log ORDER BY id DESC  ",array(),$page,$pageSize);
	}
	
	public function getUpLog($id){
		if(!$id) return false;
		return $this->db->fetchRow("SELECT * FROM cartoon_up_log WHERE id = $id");
	}
	
	public function getUpList($num = 4){
		return $this->db->fetchAll("SELECT * FROM cartoon_up_log ORDER BY id DESC LIMIT $num " );
	}
}
?>
